<script setup lang="ts">
import detailApi from '@/service/api/detail'
import PriveScroll from './components/PriveScroll.vue'
import CommentPop from '@/views/detail/components/CommentPop.vue'
// import DanmuList from '@/views/detail/components/danmuList.vue'
import downPop from '@/views/detail/components/downPop.vue'
import { getColor } from '@/enum/color'
import followApi from '@/service/api/follow'
import logApi from '@/service/api/log'

const CollDia = defineAsyncComponent(() => import('@/components/CollDia.vue'))

defineOptions({
  name: 'Detail'
})
const list = ref<any[]>([])

const route = useRoute()
const router = useRouter()

function IsPhone() {
  var info = navigator.userAgent
  return /mobile/i.test(info)
}

const isMoile = ref(IsPhone())
const pageBg = ref('https://s21.ax1x.com/2024/12/17/pAL1g54.jpg')
const getImgList = async (image_id?: number) => {
  const { data } = await detailApi.img(routeId.value)
  const newWidht = isMoile.value ? 310 : 800
  let totalHeight = 0
  list.value = data.map((el, index) => {
    const oldWidth = 750
    const oldHeight = Number(el.height)
    const newHeight = (oldHeight / oldWidth) * newWidht
    el.height = newHeight
    totalHeight += newHeight
    el.totalHeight = totalHeight
    el.show = index < 5
    return el
  })
  if (!image_id) {
    imgScroll.value?.scrollTo({
      top: 0,
      behavior: 'smooth'
    })
    addLog()
  } else {
    if (imgScroll.value) {
      nextTick(() => {
        const info = list.value.find(el => el.id === image_id)
        imgScroll.value?.scrollTo({
          top: info.totalHeight
        })
      })
    }
  }

  if (list.value.length > 0) {
    currenImg.value = list.value[0]
    pageBg.value = list.value[0].image_url
    nextTick(() => {
      priveRef.value.init()
    })
  }
}
const getZjImg = async () => {
  const { data } = await detailApi.menuImg({
    menu_id: chapterState.list[chapterState.curren].id
  })
  const newWidht = isMoile.value ? 310 : 800
  let totalHeight = 0
  list.value = data.map((el, index) => {
    const oldWidth = 750
    const oldHeight = Number(el.height)
    const newHeight = (oldHeight / oldWidth) * newWidht
    el.height = newHeight
    totalHeight += newHeight
    el.totalHeight = totalHeight
    el.show = index < 5
    return el
  })
  imgScroll.value?.scrollTo({
    top: 0,
    behavior: 'smooth'
  })
  if (list.value.length > 0) {
    currenImg.value = list.value[0]
    pageBg.value = list.value[0].image_url
    nextTick(() => {
      priveRef.value.init()
    })
  }
}
const handMenu = () => {
  if (chapterState.list.length === 0) {
    msgUtil.$message.error('暂无目录')
    return
  }
  handComeent(4)
}
let logTimer: any = null
const addLog = () => {
  if (logTimer) {
    clearTimeout(logTimer)
    logTimer = null
  }
  logTimer = setTimeout(() => {
    const params: any = {
      photo_id: routeId.value
    }
    if (currenImg.value?.id) {
      params.image_id = currenImg.value.id
    }
    logApi.add(params)
  }, 550)
}
const handNext = () => {
  if (chapterState.curren === chapterState.list.length - 1) {
    msgUtil.$message.error('已经是最后一章了')
    return
  }
  chapterChange(chapterState.curren + 1)
}
const handPre = () => {
  if (chapterState.curren === 0) {
    msgUtil.$message.error('已经是第一章了')
    return
  }
  chapterChange(chapterState.curren - 1)
}
const chapterChange = async (index: number) => {
  chapterState.curren = index
  getZjImg()
}
const info = ref<any>({
  tags: [],
  commentCount: 0,
  coll_count: 0,
  view: 0
})
const replyInfo = ref<any>({})
const getReplyUser = async () => {
  if (info.value.releaseid) {
    const { data } = await detailApi.replyUser(info.value.releaseid)
    replyInfo.value = data
  }
}
const handFollow = async () => {
  if (replyInfo.value.is_follow) {
    await followApi.cancel({
      userid: replyInfo.value.id
    })
    replyInfo.value.is_follow = false
  } else {
    await followApi.add({
      userid: replyInfo.value.id
    })
    replyInfo.value.is_follow = true
  }
}
const getDetail = async () => {
  const { data } = await detailApi.detail(routeId.value)
  data.tags = data.tags.map(el => {
    const info = getColor()
    return {
      name: el,
      ...info
    }
  })
  info.value = data
  getReplyUser()
}
let routeId = ref<string | number>('')
const chapterState = reactive({
  curren: -1,
  list: []
})
const getMenu = async () => {
  const { data } = await detailApi.menu({
    photo_id: routeId.value
  })
  chapterState.list = data
  if (data.length > 0) {
    // chapterState.curren = 0
    // getZjImg()
    router.push({
      path: '/mhdetail',
      query: {
        id: routeId.value
      }
    })
  } else {
    chapterState.curren = -1
    logApi
      .getInfo({
        photo_id: routeId.value
      })
      .then(res => {
        if (res.data?.id) {
          getImgList(res.data.image_id)
        } else {
          getImgList()
        }
      })
      .catch(() => {
        getImgList()
      })
  }
}
const init = async () => {
  nextTick(() => {
    getMenu()
    // detailApi.view(routeId.value)
    getDetail()
  })
}

const imgScroll = ref<HTMLDivElement | null>(null)
let isPriveScroll = false
const handSelect = (item: any) => {
  const itemElement = imgScroll.value?.querySelector(`[data-id="${item.id}"]`)
  if (!itemElement) return
  const top = itemElement.offsetTop
  isPriveScroll = true
  nextTick(() => {
    imgScroll.value?.scrollTo({
      top: top,
      behavior: 'smooth'
    })
    setTimeout(() => {
      isPriveScroll = false
    }, 2000)
  })
}
const priveRef = ref<any>(null)
let timer: any = null
const showImgChange = (scrollTop: number) => {
  clearTimeout(timer)
  timer = null
  const index = list.value.findIndex(el => el.totalHeight > scrollTop)
  const minIndex = index - 8
  const maxIndex = index + 8
  list.value.forEach((el, index) => {
    if (index >= minIndex && index <= maxIndex) {
      el.show = true
    }
  })
}
const currenImg = ref<any>({})
const scrollChange = () => {
  if (!imgScroll.value) return
  const scrollTop = imgScroll.value.scrollTop
  const images = imgScroll.value.querySelectorAll('img')
  let currentIndex = 0
  let minDistance = Infinity
  if (timer) {
    clearTimeout(timer)
  }
  timer = setTimeout(() => {
    showImgChange(scrollTop)
  }, 220)

  images.forEach((img, index) => {
    const imgTop = img.offsetTop
    const distance = Math.abs(imgTop - scrollTop)
    if (distance < minDistance) {
      minDistance = distance
      currentIndex = index
    }
  })
  const newCurrenImg = list.value[currentIndex]
  if (newCurrenImg.id !== currenImg.value.id) {
    currenImg.value = newCurrenImg
    addLog()
  }
  if (!isPriveScroll) {
    priveRef.value.tabChange(currentIndex)
  }
}

let loveLoading = false
const collRef = ref()
const loveChange = async () => {
  if (loveLoading) return
  if (info.value.coll) {
    loveLoading = true
    try {
      const { code, msg } = await detailApi.coll({
        id: routeId.value
      })
      if (code !== 0) {
        msgUtil.$message.error(msg)
        return
      }
      info.value.coll = !info.value.coll
      if (info.value.coll) {
        info.value.coll_count++
      } else {
        info.value.coll_count--
      }
    } finally {
      loveLoading = false
    }
  } else {
    collRef.value.open(info.value)
  }
}

const showTool = ref(true)

let lastScrollTop = 0
let showTime: any = null
const onScroll = e => {
  if (!e) return
  if (showTime) {
    clearTimeout(showTime)
    showTime = null
  }
  const scrollTop = e.target.scrollTop
  if (scrollTop > lastScrollTop) {
    showTool.value = false // Scrolling down
  } else {
    showTool.value = true // Scrolling up
    showTime = setTimeout(() => {
      if (showTool.value) {
        showTool.value = false
      }
    }, 2000)
  }
  lastScrollTop = scrollTop <= 0 ? 0 : scrollTop // For Mobile or negative scrolling
}

const commentRef = ref()
const isOpenComment = ref(false)
const { width } = useWindowSize()
const handComeent = (current?: number) => {
  if (!isMoile.value && width.value <= 1550) {
    isOpenComment.value = true
  }
  if (info.value.id) {
    commentRef.value.open(toRaw(info.value), toRaw(currenImg.value), current)
  }
}

const handUser = () => {
  if (replyInfo.value.id) {
    router.push({
      path: '/userPage',
      query: {
        id: replyInfo.value.id
      }
    })
  }
}

const downRef = ref()
const handDown = () => {
  downRef.value.open(toRaw(info.value))
}
const closeComment = () => {
  if (!isMoile.value && width.value <= 1550) {
    isOpenComment.value = false
  }
}
onMounted(() => {
  if (imgScroll.value) {
    imgScroll.value.addEventListener('scroll', onScroll)
  }
  const id = route.query.id as string
  routeId.value = id
  init()
})

const checkChange = (e: any) => {
  if (e.book_type === 1) {
    router.replace({
      path: '/mhdetail',
      query: {
        id: e.id
      }
    })
  } else {
    router.replace({
      query: {
        id: e.id
      }
    })
    routeId.value = e.id
    init()
  }
}

onBeforeUnmount(() => {
  if (imgScroll.value) {
    imgScroll.value.removeEventListener('scroll', onScroll)
  }
})
</script>

<template>
  <div class="detail" ref="detailRef" :class="{ 'detail-open': isOpenComment }">
    <div class="detail-bg">
      <img :src="pageBg" alt="" />
      <div class="mask"></div>
    </div>
    <!-- <danmu-list
      v-if="info.id"
      :pid="info.id"
      :is-open-comment="isOpenComment"
    /> -->
    <div class="left-tool" :class="{ 'left-tool-open': isOpenComment }">
      <div class="item-w">
        <div class="avatar" @click.stop="handUser">
          <img v-if="replyInfo.avatar" :src="replyInfo.avatar" alt="" />
          <div
            class="follow"
            :class="{ 'follow-cancel': replyInfo.is_follow }"
            @click.stop="handFollow"
          >
            <template v-if="replyInfo.is_follow">
              <i class="esayIcon esayIcon-hengxian"></i>
            </template>
            <template v-else>
              <i class="esayIcon esayIcon-jia"></i>
            </template>
          </div>
        </div>
      </div>
      <div class="item-w" style="margin-top: 30px">
        <div class="item">
          <i class="esayIcon esayIcon-yulan"></i>
        </div>
        <div class="num">
          <n-number-animation
            ref="numberAnimationInstRef"
            :from="0"
            :to="info.view"
          />
        </div>
      </div>
      <div class="item-w">
        <div
          class="love item"
          @click="loveChange"
          title="收藏"
          :class="{ 'love-active': info.coll }"
        >
          <span class="icon">
            <span class="TlM_il">
              <span class="IiFRN3"></span>
            </span>
            <span class="h1CBon">
              <span class="IiFRN3"></span>
            </span>
            <span class="ab2Jus">
              <span class="IiFRN3"></span>
            </span>
            <span class="GKdqLq">
              <span class="IiFRN3"></span>
            </span>
            <span class="_zh4Km"></span>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              style="width: 30px; height: 30px"
              viewBox="0 0 19 19"
              role="img"
            >
              <path
                d="M9.44985848,15.5291774 C9.43911371,15.5362849 9.42782916,15.5449227 9.41715267,15.5553324 L9.44985848,15.5291774 Z M9.44985848,15.5291774 L9.49370677,15.4941118 C9.15422701,15.7147757 10.2318883,15.0314406 10.7297038,14.6971183 C11.5633567,14.1372547 12.3827081,13.5410755 13.1475707,12.9201001 C14.3829188,11.9171478 15.3570936,10.9445466 15.9707237,10.0482572 C16.0768097,9.89330422 16.1713564,9.74160032 16.2509104,9.59910798 C17.0201658,8.17755699 17.2088969,6.78363112 16.7499013,5.65913129 C16.4604017,4.81092573 15.7231445,4.11008901 14.7401472,3.70936139 C13.1379564,3.11266008 11.0475663,3.84092251 9.89976068,5.36430396 L9.50799408,5.8842613 L9.10670536,5.37161711 C7.94954806,3.89335486 6.00516066,3.14638251 4.31830373,3.71958508 C3.36517186,4.00646284 2.65439601,4.72068063 2.23964629,5.77358234 C1.79050315,6.87166888 1.98214559,8.26476279 2.74015555,9.58185512 C2.94777753,9.93163559 3.23221417,10.3090129 3.5869453,10.7089994 C4.17752179,11.3749196 4.94653811,12.0862394 5.85617417,12.8273544 C7.11233096,13.8507929 9.65858244,15.6292133 9.58280954,15.555334 C9.53938013,15.5129899 9.48608859,15.5 9.50042471,15.5 C9.5105974,15.5 9.48275828,15.5074148 9.44985848,15.5291774 Z"
              ></path>
            </svg>
          </span>
        </div>
        <div class="num">
          <n-number-animation
            ref="numberAnimationInstRef"
            :from="0"
            :to="info.coll_count"
          />
        </div>
      </div>
      <div class="item-w">
        <div class="item" title="评论" @click="handComeent()">
          <i class="esayIcon esayIcon-comment"></i>
        </div>
        <div class="num">
          <n-number-animation
            ref="numberAnimationInstRef"
            :from="0"
            :to="info.commentCount"
          />
        </div>
      </div>
      <div class="item-w" v-if="info.buy">
        <div class="item" title="下载" @click="handDown">
          <i class="esayIcon esayIcon-download-1-copy"></i>
        </div>
      </div>
      <div class="item-w" v-else>
        <div class="item" title="购买" @click="handDown">
          <i class="esayIcon esayIcon-renwuzhongxin-goumaishangpin"></i>
        </div>
      </div>
    </div>
    <div class="detail-main" ref="imgScroll" @scroll="scrollChange">
      <div class="img-w" v-for="item in list" :key="item.id" :data-id="item.id">
        <template v-if="item.show">
          <n-image
            :height="item.height"
            preview-disabled
            lazy
            :src="item.image_url"
            bject-fit="cover"
            fallback-src="https://07akioni.oss-cn-beijing.aliyuncs.com/07akioni.jpeg"
          >
            <template #placeholder>
              <div
                class="img-placeholder"
                :style="{ height: item.height + 'px' }"
              >
                <common-loading />
              </div>
            </template>
          </n-image>
        </template>
        <template v-else>
          <div class="img-placeholder" :style="{ height: item.height + 'px' }">
            <common-loading />
          </div>
        </template>
      </div>
      <div class="charper-menu">
        <div class="btn" @click="handMenu">目录</div>
        <div class="btn" @click="handPre">上一章</div>
        <div class="btn" @click="handNext">下一章</div>
      </div>
    </div>
    <template v-if="chapterState.list.length > 0">
      <div class="charper-tool" :class="{ 'charper-tool-open': isOpenComment }">
        <div class="btn" @click="handMenu">目录</div>
        <div class="btn" @click="handPre">上一章</div>
        <div class="btn" @click="handNext">下一章</div>
      </div>
    </template>
    <div class="bottom" style="color: red" v-if="list.length > 0">
      <prive-scroll ref="priveRef" :list="list" @select="handSelect" />
    </div>
    <comment-pop
      :replyInfo="replyInfo"
      :chapterIndex="chapterState.curren"
      :chapterList="chapterState.list"
      ref="commentRef"
      @close="closeComment"
      @check="checkChange"
      @follow="handFollow"
      @change="chapterChange"
    />
    <down-pop ref="downRef" @success="init" />
    <coll-dia ref="collRef" @success="init" />
  </div>
</template>

<style scoped lang="scss">
@keyframes qrbXQX {
  0% {
    transform: scale(1);
  }
  40% {
    transform: scale(1.3);
  }
  70% {
    transform: scale(0.9);
  }
  90% {
    transform: scale(1.1);
  }
  100% {
    transform: scale(1);
  }
}

@keyframes kWXE2n {
  0% {
    opacity: 0.1;
    transform: scale(0.1);
  }
  20% {
    opacity: 1;
  }
  to {
    opacity: 0;
    transform: scale(1.5);
  }
}

@keyframes e1MjpB {
  0% {
    opacity: 0;
    transform: translateX(5px) scale(1);
  }
  20% {
    opacity: 1;
  }
  to {
    opacity: 0;
    transform: translateX(17px) scale(0);
  }
}

.detail {
  height: 100%;
  background-color: #212121;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow-y: scroll;
  transition: padding-right 0.3s;

  &-open {
    padding-right: 300px;
  }

  &-bg {
    z-index: 0;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    overflow: hidden;

    img {
      filter: blur(60px);
      opacity: 0.8;
      width: 100%;
      height: 100%;
      user-select: none;
      transform: scale(1.2);
    }

    .mask {
      z-index: -1;
      background-color: #000;
      position: absolute;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
    }
  }

  .left-tool {
    position: fixed;
    z-index: 9;
    right: calc(50vw - 400px - 70px);
    transition: right 0.3s;
    top: 80px;
    display: flex;
    flex-direction: column;
    align-items: center;

    &-open {
      right: calc(50vw - 400px - 60px + 150px);
    }

    .item-w {
      position: relative;
      &:not(:first-child) {
        margin-top: 20px;
      }

      .avatar {
        width: 46px;
        height: 46px;

        img {
          width: 100%;
          height: 100%;
          transition: all 0.3s;
          object-fit: cover;
          cursor: pointer;
          border-radius: 50%;
        }
        &:hover {
          img {
            transform: scale(1.1);
          }
        }
      }

      .follow {
        position: absolute;
        left: 50%;
        bottom: -10px;
        transform: translateX(-50%);
        color: #fff;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: #e84a43;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        i {
          font-size: 13px;
        }
        .esayIcon-hengxian {
          font-size: 28px;
        }
        &-cancel {
          background: orange;
        }
      }

      .item {
        width: 30px;
        height: 30px;
        background-color: rgba(255, 255, 255, 0.9);
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;

        i {
          font-size: 16px;
        }
      }

      .num {
        text-align: center;
        padding-top: 2px;
        color: #fff;
        font-size: 12px;
        text-shadow: rgba(0, 0, 0, 0.2) 0px 1px 1px;
      }
    }

    .love {
      display: flex;
      align-items: center;

      span {
        font-size: 12px;
      }

      .icon {
        width: 20px;
        position: relative;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      svg {
        fill: transparent;
        stroke: #333;
        stroke-width: 1.5px;
        transition: fill 0.25s;
      }

      .TlM_il {
        transform: rotate(0deg);
        display: inline-block;
        height: 6px;
        inset-inline-start: 8px;
        position: absolute;
        top: 7px;
        width: 6px;
        border-radius: 50%;
      }

      .h1CBon {
        display: inline-block;
        height: 6px;
        inset-inline-start: 8px;
        position: absolute;
        top: 7px;
        width: 6px;
        transform: rotate(144deg);
        border-radius: 50%;
      }

      .ab2Jus {
        display: inline-block;
        height: 6px;
        inset-inline-start: 8px;
        position: absolute;
        top: 7px;
        width: 6px;
        transform: rotate(216deg);
        border-radius: 50%;
      }

      .GKdqLq {
        transform: rotate(288deg);
        display: inline-block;
        inset-inline-start: 8px;
        position: absolute;
        top: 7px;
        height: 6px;
        width: 6px;
      }

      ._zh4Km {
        display: none;
      }

      &-active {
        svg {
          fill: #e84a43;
          stroke: none;
          opacity: 1;
          display: inline-block;
          position: relative;
          animation: qrbXQX 0.5s;
        }

        .IiFRN3 {
          display: inline-block;
          opacity: 0;
          position: absolute;
          animation: e1MjpB 0.5s;
          animation-delay: 0.1s;
          border-radius: 50%;
          height: 4px;
          inset-inline-start: 8px;
          top: 7px;
          width: 4px;
          background-color: #e84a43;
        }

        ._zh4Km {
          animation: kWXE2n 0.3s;
          display: inline-block;
          opacity: 0;
          position: absolute;
          border: 3px solid #e84a43;
          border-radius: 100%;
          height: 24px;
          inset-inline-start: -3px;
          top: -3px;
          width: 24px;
        }
      }
    }
  }

  &-main {
    flex: 1 0 0;
    width: 800px;
    margin: 0 auto;
    background-color: #212121;
    overflow: auto;
    position: relative;

    .img-w {
      width: 100%;
      overflow: hidden;
    }

    .charper-menu {
      display: none;
    }

    img {
      width: 100%;
      display: block;
    }
  }

  .charper-tool {
    position: fixed;
    z-index: 9;
    right: calc(50vw - 400px - 70px);
    transition: right 0.3s;
    bottom: 100px;
    display: flex;
    flex-direction: column;
    align-items: center;
    &-open {
      right: calc(50vw - 400px - 60px + 150px);
    }
    .btn {
      padding: 10px;
      cursor: pointer;
    }
  }

  .bottom {
    width: 800px;
    margin: 10px auto;
    padding: 0 20px;
    box-sizing: border-box;
    background-color: rgba(89, 89, 89, 0.25);
    backdrop-filter: blur(6px);
    -webkit-backdrop-filter: blur(6px);
    border: 1px solid rgba(255, 255, 255, 0.18);
    box-shadow: rgba(14, 14, 14, 0.19) 0 6px 15px 0;
    -webkit-box-shadow: rgba(14, 14, 14, 0.19) 0 6px 15px 0;
    border-radius: 12px;
    -webkit-border-radius: 12px;
    color: rgb(128, 128, 128);
  }

  .tool-btn {
    position: fixed;
    right: 20px;
    bottom: 20px;
    background-color: rgba(0, 0, 0, 0.95);
    border-radius: 40px;
    border: 1px solid rgb(62, 62, 62);
    color: rgba(255, 255, 255, 0.7);
    font-weight: 400;
    font-size: 14px;
    padding: 8px 24px;
    cursor: pointer;
  }
}

@media (max-width: 800px) {
  .detail {
    .left-tool {
      width: 25px;
      left: 20px;
      top: 20px;
      .item-w {
        &:not(:first-child) {
          margin-top: 10px;
        }

        .item {
          width: 25px;
          height: 25px;
          i {
            font-size: 14px;
          }
        }

        .num {
          font-size: 10px;
        }
      }
      .love {
        .icon {
          width: 14px;
        }
      }
    }

    .charper-tool {
      display: none;
    }
    .charper-menu {
      display: flex;
      align-items: center;
      justify-content: center;
      background: #fff;
      .btn {
        padding: 5px 0;
        flex: 1;
        cursor: pointer;
        text-align: center;
        font-size: 13px;
        &:not(:last-child) {
          border-right: 1px solid rgba(0, 0, 0, 0.1);
        }
      }
    }

    &-main {
      width: 310px;
    }

    .bottom {
      width: 310px;
    }

    .tool-btn {
      font-size: 12px;
      bottom: 130px;
      display: none;
    }
  }
}
</style>
<style lang="scss">
.detail .n-image {
  width: 100%;
  height: 100%;

  img {
    width: 100%;
    display: block;
  }
}

.img-placeholder {
  background-color: #000;
  position: relative;
  width: 100%;
  display: flex;
  justify-content: center;
  padding-top: 30px;
}
</style>
